﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Groundwork.Extensions
{
    public static class Streams
    {
        /// <summary>
        /// Converts a steam into a human readable string
        /// </summary>
        /// <param name="stream">stream to convert</param>
        /// <returns>converted string</returns>
        public static string ToString(this Stream stream)
        {
            byte[] tmp = ReadStream(stream);
            return Encoding.UTF8.GetString(tmp);
        }

        /// <summary>
        /// Readers a given stream and outputs a byte array of the input stream
        /// </summary>
        /// <param name="stream">stream to read</param>
        /// <returns>stream converted to a byte array</returns>
        private static byte[] ReadStream(Stream stream)
        {
            long originalPosition = stream.Position;
            stream.Position = 0;

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }

                return buffer;
            }
            finally
            {
                stream.Position = originalPosition;
            }
        }

    }
}
